import Taro from "@tarojs/taro";
import { companyName, currentPlatForm, getRuntime, ServerHost, uploadUrl } from './common';
import mui from '../assets/mui/mui.min'


class Runtime {
  /**
   *
   * 设置存储
   * @param {any} info
   */
  setStorage = (key: string, value?: object) => {
    Taro.setStorageSync(key, value ? JSON.stringify(value) : "");
  }

  /**
   *
   * 获取存储
   * @returns
   */
  getStorage = (key: string) => {
    var data = Taro.getStorageSync(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  /**
   *
   * 设置用户信息
   * @param {any} info
   */
  setUserInfo = (info?: any) => {
    Taro.setStorageSync("user", info ? JSON.stringify(info) : "");
  }

  /**
   *
   * 获取用户信息
   * @returns
   */
  getUserInfo = () => {
    var data = Taro.getStorageSync("user");
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  /**
   * 获取token
   */
  getToken = () => {
    const user = this.getUserInfo();
    if (!user) return ''
    return { Authorization: "Bearer " + (user && user.token || '') };
    //return { Authorization: "Bearer HDZ1zkJ9xyj_DjH-VdDATOkdF5XlzBRiBNr7x3T0uuqBd8QPYaKvPFGKgQ5bJaU9Bhw5Qde4fSbJANr3Oddme5bS2C-KVa3irOxOWyWgHPZt6ZTUDJKqkJG3xHPIhGiPi3fnwV-HzZDc5ySU0svm97k6cQf3eBpVlJILkQrF9ftxNeZ7PBHAAFtNno8R-Nls3rnyLjJHun1FuZnCWlQkKzsHT2a7qgU-o5xXBPcS7gzuPzE2A30HvWvCBWeRAk9g7kODhb2-L6hG-Q8UwdyDf5w1cBqwyIKmThE0kaC2D91ERp6TImz1ULZleS6wOtp8O6Za8dQF9tEfELn-yT5xE6sPWLrb4ya-vfUgwDD3H6OCHZbpKOKt985kOLFfNApBOjyNNG8eqcvZqt7eWq4a4YZ-z1qK9FNrkq_dtS4a_vsakeT-hqxH3EdIWy0bu2q_4vr97mM7FbizEALR8K0LpTEMlqrM1Pjkfm0ms95djYBvUiS4weBtC903-X94_4Oz" };
  }

  isLogin = () => {
    if (!localStorage.token) {
      // return false;
      return "请先登录";
    } else {
      return true;
    }
  }

  navigateTo = (url: string) => {
    if (currentPlatForm === 'h5App') {
      this.navigateToH5App(url)
    } else {
      this.navigateToTaro(url)
    }
  }

  navigateToTaro = (url: string) => {
    let isNeedLogin = false
    let pagePaths = Taro.getApp().state.pagesArr || []
    pagePaths.map(item => {
      if ('/' + item.url === url) {
        isNeedLogin = item.isLogin
      }
    })
    if (!getRuntime().getToken() && isNeedLogin) {
      getRuntime().navigateTo('/pages/other/bindPhone'); return
    }
    Taro.navigateTo({
      url: url
    });
  }

  // hbuilderx打包App跳转
  navigateToH5App = (url: string) => {
    let platForm = process.env.TARO_ENV // 通过hbuilderx打包成app之后的平台信息还是h5
    mui.toast('平台：' + platForm)
    let pagePaths = Taro.getApp().state.pagesArr || []
    let fullUrl = ServerHost + '/m/#/pages/index/index'
    let id: string = 'index'
    let title: string = companyName
    let isNeedLogin = false
    let hash = window.location.hash
    pagePaths.map(item => {
      if ('#/' + item.url === hash) {
        fullUrl = ServerHost + '/m/#/' + item.url
        id = item.name
        title = item.title
        isNeedLogin = item.isLogin
      }
    })
    if (!getRuntime().getToken() && isNeedLogin) {
      fullUrl = ServerHost + '/m/#/pages/other/bindPhone'
    }

    let webview = plus.webview.create(fullUrl, id, {
      'titleNView': {                       // 窗口的标题栏控件
        titleText: title,                // 标题栏文字,当不设置此属性时，默认加载当前页面的标题，并自动更新页面的标题
        titleColor: "#ffffff",             // 字体颜色,颜色值格式为"#RRGGBB",默认值为"#000000"
        titleSize: "17px",                 // 字体大小,默认17px
        backgroundColor: "#00d9c6",        // 控件背景颜色,颜色值格式为"#RRGGBB",默认值为"#F7F7F7"
        autoBackButton: true,
        progress: {                        // 标题栏控件的进度条样式
          color: "#ffffff",                // 进度条颜色,默认值为"#00FF00"
          height: "2px"                    // 进度条高度,默认值为"2px"
        },
        splitLine: {                       // 标题栏控件的底部分割线，类似borderBottom
          color: "#dddddd",                // 分割线颜色,默认值为"#CCCCCC"
          height: "1px"                    // 分割线高度,默认值为"2px"
        }
      }
    })
    webview.addEventListener('close', function () {
      webview = null;
    });
    webview.addEventListener('titleUpdate', function () {
      webview.show();
    });

    /*  mui.openWindow({
        url: fullUrl,
        id,
        extras:{ }, //自定义扩展参数，可以用来处理页面间传值},
        createNew: true,//是否重复创建同样id的webview，默认为false:不重复创建，直接显示
        show:{
          autoShow:true,//页面loaded事件发生后自动显示，默认为true
        },
        waiting:{
          autoShow:true,//自动显示等待框，默认为true
          title:'正在加载...',//等待对话框上显示的提示内容
        },
        styles: {                             // 窗口参数 参考5+规范中的WebviewStyle,也就是说WebviewStyle下的参数都可以在此设置
          titleNView: {                       // 窗口的标题栏控件
            titleText: title,                // 标题栏文字,当不设置此属性时，默认加载当前页面的标题，并自动更新页面的标题
            titleColor:"#ffffff",             // 字体颜色,颜色值格式为"#RRGGBB",默认值为"#000000"
            titleSize:"17px",                 // 字体大小,默认17px
            backgroundColor:"#00d9c6",        // 控件背景颜色,颜色值格式为"#RRGGBB",默认值为"#F7F7F7"
            progress:{                        // 标题栏控件的进度条样式
              color:"#ffffff",                // 进度条颜色,默认值为"#00FF00"
              height:"2px"                    // 进度条高度,默认值为"2px"
            },
            splitLine:{                       // 标题栏控件的底部分割线，类似borderBottom
              color:"#dddddd",                // 分割线颜色,默认值为"#CCCCCC"
              height:"1px"                    // 分割线高度,默认值为"2px"
            }
          }
        }
      })*/
  }

  redirectTo = (url: string) => {
    Taro.redirectTo({
      url: url
    });
  }

  navigateBack = () => {
    Taro.navigateBack({
      delta: 1
    });
  }

  switchTab = (url: string) => {
    Taro.switchTab({
      url: url
    })
  }

  pageScrollToTop = () => {
    Taro.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  }

  pageScrollTo = (scrollTop) => {
    Taro.pageScrollTo({
      scrollTop: scrollTop,
      duration: 300,
    });
  }

  showToast = (title: string, icon?: string) => {
    Taro.showToast({
      title: title,
      icon: icon || 'none',
      mask: true,
    });
  };

  showModal = (title, content: string = '', callback: () => void) => {
    Taro.showModal({
      title: title,
      content: content,
    })
      .then(res => {
        if (res.confirm) {
          callback()
        }
      });
  }

  makePhoneCall = (phoneNumber: string) => {
    Taro.makePhoneCall({
      phoneNumber: phoneNumber,
    })
  }

  wxloginout = () => {
    this.setUserInfo();
    Taro.clearStorage();
  };

  wxlogin = (res, getToken: (any) => void, fail: () => void) => {
    const user = this.getUserInfo();
    if (user) return;
    const that = this;
    Taro.login({
      success: function (loginres) {
        if (loginres.code && res.encryptedData) {
          that.setStorage("code", { code: loginres.code });
          const info = {
            code: loginres.code,
            ...res,
          };
          console.log(info);
          getToken(info);
        } else {
          fail();
        }
      }
    });
  };

  getwxcode = (callback: (code: string) => void) => {
    Taro.login({
      success: function (loginres) {
        callback(loginres.code);
      }
    });
  }

  wxauth = (name: string, callback: (auth: boolean) => void) => {
    Taro.getSetting({}).then(res => {
      if (res.authSetting[name]) {
        callback(true);
      } else {
        callback(false);
      }
    }).catch((e) => {
      callback(false);
    })
  }


  upload = (callback, count = 1) => {
    Taro.chooseImage({
      count: count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })
      .then(res => {
        Taro.showLoading({
          title: '拼命上传中...'
        })
        let tempFiles = res.tempFiles[0]
        this.imgCompressed(tempFiles.path, tempFiles.size, (filePath) => {
          Taro.uploadFile({
            url: ServerHost + uploadUrl,
            header: this.getToken(),
            filePath: filePath,
            name: 'file'
          })
            .then(res1 => {
              Taro.hideLoading()
              if (res1.statusCode == 200) {
                const data = JSON.parse(res1.data);
                if (data.success) {
                  callback(data.result);
                  // this.setState({ avatar: data.result });
                } else {
                  this.showToast(data.error.message, 'none');
                }
              } else {
                this.showToast(res1['errMsg'], 'none');
              }
            });
        })
      });
  }

  // 图片压缩
  imgCompressed = (imgPath: string, imgSize: number, callBack?) => {
    let that = this
    let quality = 1
    // 大于1M的压缩
    let sizeM = imgSize / 1024 / 1024
    console.log(sizeM)
    if (sizeM < 1) {
      // 不压缩
      quality = 1
      callBack(imgPath)
      return
    }
    else if (sizeM >= 1 && sizeM < 2) { quality = 0.95 }
    else if (sizeM >= 2 && sizeM < 3) { quality = 0.92 }
    else { quality = 0.8 }
    let image = document.createElement('img')
    image.crossOrigin = 'Anonymous'
    image.onload = function () {
      let canvas = document.createElement("canvas")
      canvas.width = image.width
      canvas.height = image.height
      let ctx = canvas.getContext("2d")
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
      /**
       * 本来打算使用toBlob函数进行压缩，因为Taro的chooseImage函数返回的图片路径是blob类型的文件，可是toBlob函数不知道什么原因，并不能返回blob文件。于是打算转换成base64
       * 的图片，没想到也是可以上传的
       */
      // 转化成blob文件
      // 第一个参数回调，第二个参数图片类型(image/png; image/jpeg)默认为image/png；第三个参数图片质量（0~1）取值
      canvas.toBlob((blobFile) => {
        // blob数据转化成
        let url = URL.createObjectURL(blobFile)
        callBack && callBack(url)
      }, 'image/jpeg', 0.92)
      let dataUrl = canvas.toDataURL('image/jpeg', quality)
      if (!dataUrl) { that.showToast('图片上传压缩失败, 请重试!'); return }
      callBack && callBack(dataUrl)
    }
    image.src = imgPath
  }

  /**
   * 图片上传
   * @param files
   * @param callback
   */
  uploadFile = (files: Array<string>, callback: (urls: string[]) => void) => {
    let images = Array<string>();
    for (var i = images.length; i < files.length; i++) {
      const file = files[i]['file']['path'];
      Taro.showLoading({ title: '图片上传中...' })
      Taro.uploadFile({
        url: ServerHost + uploadUrl,
        header: this.getToken(),
        filePath: file,
        name: 'file'
      })
        .then(res1 => {
          Taro.hideLoading()
          if (res1.statusCode == 200) {
            const data = JSON.parse(res1.data);
            if (data.success) {
              images.push(data.result);
              if (images.length == files.length)
                this.showToast('图片上传成功~')
              callback(images);
            }
            else {
              this.showToast(data.error.message, 'none');
            }
          }
          else {
            this.showToast(res1['errMsg'], 'none');
          }
        }).catch(error => {
          Taro.hideLoading()
          console.log(error)
        })
    }
  }



  //下拉刷新
  pullDownRefresh = (callback) => {
    Taro.showNavigationBarLoading() //在标题栏中显示加载
    callback();
    Taro.hideNavigationBarLoading() //在标题栏中显示加载
    Taro.stopPullDownRefresh();
  }

  createSelectorQuery = (): Taro.SelectorQuery => {
    return Taro.createSelectorQuery();
  }

  scanCode = (callback: (string) => void) => {
    Taro.scanCode().then(res => {
      callback(res.result);
    });
  }

  getLocation = (callback: (latitude, longitude) => void) => {
    Taro.getLocation({
      type: 'wgs84'
    }).then(res => {
      callback(res.latitude, res.longitude);
    });
  }

  chooseLocation = (callback: (name, address, latitude, longitude) => void) => {
    Taro.chooseLocation().then(res => {
      callback(res.name, res.address, res.latitude, res.longitude);
    });
  }

  openLocation = (latitude, longitude) => {
    Taro.openLocation({ latitude, longitude });
  }

  wxPay = (payParams, callback: () => void) => {
    const that = this;
    Taro.requestPayment({
      timeStamp: payParams.timeStamp,
      nonceStr: payParams.nonceStr,
      package: payParams.package,
      signType: payParams.signType,
      paySign: payParams.paySign,
      success(res) {
        // console.log(res);
        callback();
      },
      fail(res) {
        console.log(res);
        that.showToast("支付失败");
      }
    })
  }

  isEmpty = (str) => {
    if (typeof str == "undefined" || str == null || str == "") {
      return true;
    }
    return false;
  }

  commonPay(orderId: number, custom: number, isPayPoints: boolean = false, callBack) {
    let payUrl = `${ServerHost}/api/Account/PaymentParameters?orderId=${orderId}&custom=${custom}&isPayPoint=${isPayPoints}`
    let user = getRuntime().getUserInfo()
    let token = user && user.token ? 'Bearer ' + user.token : ''
    fetch(payUrl, {
      method: 'GET',
      headers: { 'Authorization': token }
    })
      .then(response => response.json())
      .then(response => {
        console.log(response)
        if (response.msg === 'ok') {
          getRuntime().wxPay(response, () => {
            callBack && callBack()
          })
        } else {
          getRuntime().showToast(response.msgtext);
        }
      })
      .catch(() => {
        getRuntime().showToast('获取支付参数失败~');
      })
  }
}


export { Runtime }
